package com.sgb.jicai.view.activity;

import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;

import com.sgb.jicai.R;
import com.sgb.jicai.databinding.ActivityJiCaiSearchBinding;
import com.sgb.jicai.viewmodel.JcChanceListModel;
import com.sgb.jicai.viewmodel.JiCaiSearchModel;
import com.swgk.core.base.AppActivity;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SharedPreferenceUtil;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;
import com.zhy.view.flowlayout.TagFlowLayout;
import java.util.List;

public class JiCaiSearchActivity extends AppActivity {

    JiCaiSearchModel model;
    private ActivityJiCaiSearchBinding binding;

    private TagAdapter historyAdapter;
    private TagAdapter hotAdapter;
    private InputMethodManager im;

    public static void start(Context context) {
        Intent intent = new Intent();
        intent.setClass(context, JiCaiSearchActivity.class);
        context.startActivity(intent);
    }


    @Override
    protected void initView() {
        binding = DataBindingUtil.setContentView(this, R.layout.activity_ji_cai_search);
        model = new ViewModelProvider(this).get(JiCaiSearchModel.class);
        model.setActivity(JiCaiSearchActivity.this);
        binding.setViewModel(model);
        binding.ivBack.setOnClickListener(this);
        binding.tvSearch.setOnClickListener(this);
        binding.ivDelete.setOnClickListener(this);
        im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    }

    @Override
    protected void init() {
        model.getSearchHistoryListData();
        model.getSearchHotListData();

        binding.editSearch.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
                    if (TextUtils.isEmpty(binding.editSearch.getText().toString())) {
//                        MToast.showToast(JiCaiSearchActivity.this, "请输入关键字");
                        MToast.showToast(JiCaiSearchActivity.this, "请输入关键字");
                        return true;
                    }
                    goSearch(binding.editSearch.getText().toString().trim());
                    recordsLocal(binding.editSearch.getText().toString().trim());
                }
                return false;
            }
        });

    }

    //设置历史搜索词汇
    public void setSearchHistoryData(List<String> ls) {
        if (ls!=null&&ls.size()>0){
            binding.llSearchHistory.setVisibility(View.VISIBLE);
            binding.searchHistoryList.setVisibility(View.VISIBLE);
            final LayoutInflater mInflater = LayoutInflater.from(JiCaiSearchActivity.this);
            historyAdapter = new TagAdapter<String>(ls) {
                @Override
                public View getView(FlowLayout parent, int position, String s) {
                    LinearLayout layout = (LinearLayout) mInflater.inflate(R.layout.item_jicai_search_words, binding.searchHistoryList, false);
                    TextView tv = layout.findViewById(R.id.name);
                    tv.setText(s);
                    return layout;
                }
            };
            binding.searchHistoryList.setAdapter(historyAdapter);
            binding.searchHistoryList.setOnTagClickListener(new TagFlowLayout.OnTagClickListener() {
                @Override
                public boolean onTagClick(View view, int position, FlowLayout parent) {
                    MToast.showToast(JiCaiSearchActivity.this, "搜索：" + ls.get(position));
                    goSearch(ls.get(position));
                    recordsLocal(ls.get(position));
                    return true;
                }
            });
        }else {
            binding.llSearchHistory.setVisibility(View.GONE);
            binding.searchHistoryList.setVisibility(View.GONE);
        }

    }

    //设置热搜搜索词汇
    public void setHotHistoryData(List<String> ls) {
        final LayoutInflater mInflater = LayoutInflater.from(JiCaiSearchActivity.this);
        hotAdapter = new TagAdapter<String>(ls) {
            @Override
            public View getView(FlowLayout parent, int position, String s) {
                LinearLayout layout = (LinearLayout) mInflater.inflate(R.layout.item_jicai_search_words, binding.searchHistoryList, false);
                TextView tv = layout.findViewById(R.id.name);
                tv.setText(s);
                return layout;
            }
        };
        binding.searchHotList.setAdapter(hotAdapter);
        binding.searchHotList.setOnTagClickListener(new TagFlowLayout.OnTagClickListener() {
            @Override
            public boolean onTagClick(View view, int position, FlowLayout parent) {
                Log.v("search=", ls.get(position));
                goSearch(ls.get(position));
                recordsLocal(ls.get(position));
                return true;
            }
        });
    }

    private void goSearch(String words) {
        model.search(words);
        jumpJcdtPage(words);
    }

    //跳转进集采大厅 \ 关闭自己
    private void jumpJcdtPage(String words) {
        JiCaiSearchTwoActivity.start(getActivity(), words);//集采二级搜索界面
       // finish();//这里是否可关闭需测试
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        int id = v.getId();
        if (id == R.id.iv_back) {
            finish();
        } else if (id == R.id.tv_search) {
            if (binding.editSearch.getText().toString().isEmpty()) {
//                    MToast.showToast(JiCaiSearchActivity.this, "请输入关键字");
                MToast.showToast(JiCaiSearchActivity.this, "请输入关键字");
            } else {
                goSearch(binding.editSearch.getText().toString().trim());
                recordsLocal(binding.editSearch.getText().toString().trim());
            }
        } else if (id == R.id.iv_delete) {
            cleanHistoryWord();
        }
    }

    //将搜索词汇记录在本地
    private void recordsLocal(String newWords) {
        String historyWords = SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.JICAI_SEARCH_HISTORY, "");
        StringBuffer oldWords = new StringBuffer();
        if (null != historyWords && !historyWords.isEmpty()) {
            String[] arr = historyWords.split(","); //字符串转数组,  用,分割
            for (int i = 0; i < arr.length; i++) {
                if (i < 10) {//最多只记录10条
                    if (newWords.equals(arr[i])) {
                        //剔除相同的字符
                    } else {
                        oldWords.append(arr[i] + ",");
                    }
                }
            }
        }
        String allHistoryWords = newWords + "," + String.valueOf(oldWords);
        SharedPreferenceUtil.getInstance().saveString(SharedPreferenceUtil.JICAI_SEARCH_HISTORY, allHistoryWords);
//        model.getSearchHistoryListData();
    }

    //清除本地搜索记录
    private void cleanHistoryWord() {
        SharedPreferenceUtil.getInstance().saveString(SharedPreferenceUtil.JICAI_SEARCH_HISTORY, "");
        model.getSearchHistoryListData();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        closeKeybord();
    }

    //关闭软键盘
    protected void closeKeybord() {
        if (this.getCurrentFocus() != null) {
            ((InputMethodManager) getActivity().getSystemService(getActivity().INPUT_METHOD_SERVICE))
                    .hideSoftInputFromWindow(this.getCurrentFocus()
                                    .getWindowToken(),
                            InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

}
